from paddleocr import PaddleOCR, draw_ocr
import numpy as np
import cv2
from PIL import Image, ImageDraw, ImageFont

def main():
    # 初始化 PaddleOCR
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
    
    # 读取图片文件
    img_path = r'D:\code\video-scan\resource\test01_cropped.jpg'
    
    # 进行文字识别
    result = ocr.ocr(img_path, cls=True)
    
    # 读取原始图像并转换为PIL格式
    image = cv2.imread(img_path)
    image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(image_pil)
    
    # 加载中文字体，调整字体大小
    font_path = "C:/Windows/Fonts/simhei.ttf"
    font_size = 12  # 减小字体大小
    font = ImageFont.truetype(font_path, font_size)
    
    # 在识别区域绘制文本
    for line in result[0]:
        box = np.array(line[0], dtype=np.int32)
        text = line[1][0]
        
        # 计算文本框大小
        text_width = max(point[0] for point in box) - min(point[0] for point in box)
        text_height = max(point[1] for point in box) - min(point[1] for point in box)
        
        # 根据文本框大小动态调整字体
        font_size = min(int(text_height * 0.8), 12)  # 限制最大字号
        font = ImageFont.truetype(font_path, font_size)
        
        # 绘制白色背景
        draw.polygon([tuple(p) for p in box], fill=(255, 255, 255))
        
        # 计算文本位置，稍微向下偏移
        x = min(point[0] for point in box)
        y = min(point[1] for point in box) + 2  # 向下偏移2像素
        
        # 绘制中文文本
        draw.text((x, y), text, font=font, fill=(0, 0, 0))
    
    # 转换回OpenCV格式并保存
    image_cv = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
    cv2.imwrite('result_combined.jpg', image_cv)

if __name__ == "__main__":
    main()